// pages/cart/component/cart.js
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { userStore } from '@/stores/userStore'
const computedBehavior = require('miniprogram-computed').behavior
import { swiperCellBehavior } from '@/behaviors/swiperCell'
import { debounce } from 'miniprogram-licia'
import {
  CheckAllApi,
  updateCheckCartApi,
  getCartListApi,
  DelCartApi,
  AddtoCartApi
} from '@/api/cart'
ComponentWithStore({
  behaviors: [computedBehavior, swiperCellBehavior],
  storeBindings: {
    store: userStore,
    fields: ['token']
  },
  // 组件的属性列表
  properties: {},
  computed: {
    isCheckAll(data) {
      return (
        data.cartList.length !== 0 &&
        data.cartList.every((item) => item.isChecked === 1)
      )
    },
    totalPrice(data) {
      let totalPrice = 0
      // 累加订单总金额
      data.cartList.forEach((item) => {
        if (item.isChecked === 1) {
          totalPrice += item.price * item.count
        }
      })
      return totalPrice
    }
  },
  // 组件的初始数据
  data: {
    cartList: [],
    emptyDes: '还没有添加商品，快去添加吧～'
  },
  // 组件的方法列表
  methods: {
    toOrder() {
      if (this.data.totalPrice === 0) {
        wx.toast({
          title: '请选择需要购买的商品'
        })
        return
      }
      wx.navigateTo({
        url: '/modules/orderPayModule/pages/order/detail/detail'
      })
    },
    changeBuyNum: debounce(async function (e) {
      // console.log(e)
      const newbuynum = e.detail > 200 ? 200 : e.detail
      const { id, index, oldbuynum } = e.currentTarget.dataset
      const reg = /^([1-9]|[1-9]\d|[1-9]\d{2}|200)$/
      // 对用户输入的值进行验证
      const regRes = reg.test(newbuynum)
      if (!regRes) {
        this.setData({
          [`cartList[${index}].count`]: oldbuynum
        })
        return
      } else {
        const disCount = newbuynum - oldbuynum
        if (disCount !== 0) {
          // 购买数量发生了改变
          const res = await AddtoCartApi({ goodsId: id, count: disCount })
          // console.log(res)
          if (res.code === 200) {
            this.setData({
              [`cartList[${index}].count`]: newbuynum,
              [`cartList[${index}].isChecked`]: 1
            })
          }
        }
      }
    }, 500),
    async CheckAll(e) {
      // console.log(e)
      const { detail } = e
      const isChecked = detail ? 1 : 0
      const res = await CheckAllApi(isChecked)
      if (res.code === 200) {
        // this.showTipGetList()
        const newCartList = JSON.parse(JSON.stringify(this.data.cartList)) //对购物车数据进行深拷贝
        newCartList.forEach((item) => (item.isChecked = isChecked))
        this.setData({
          cartList: newCartList
        })
      }
    },
    async updateCheck(e) {
      console.log(e)
      const { detail } = e
      const { id, index } = e.currentTarget.dataset
      const isChecked = detail ? 1 : 0
      const res = await updateCheckCartApi(id, isChecked)
      // console.log(res)
      // if (res.code === 200) this.showTipGetList()
      if (res.code === 200) {
        this.setData({
          [`cartList[${index}].isChecked`]: isChecked
        })
      }
    },
    async showTipGetList() {
      const { token } = this.data
      if (!token) {
        this.setData({
          emptyDes: '您尚未登录,点击登录获取更多权益',
          cartList: []
        })
        return
      } else {
        const res = await getCartListApi()
        // console.log(res)
        if (res.code === 200) {
          this.setData({
            cartList: res.data,
            emptyDes:
              res.data.length === 0 ? '还没有添加商品，快去添加吧～' : ''
          })
        }
      }
    },
    async delCart(event) {
      // console.log(event)
      const modalRes = await wx.modal({ title: '您确认删除该商品吗?' })
      if (modalRes) {
        const { goodsid } = event.currentTarget.dataset
        const res = await DelCartApi(goodsid)
        // console.log(res)
        this.showTipGetList()
      } else {
        return
      }
    },
    onShow() {
      this.showTipGetList()
    },
    onHide() {
      this.onSwiperCellCommonClick()
    }
  }
})
